#!/bin/bash

# YxYWeb 环境变量测试脚本
# 用于验证 .env 文件配置是否正确

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 检查.env文件
check_env_file() {
    print_step "检查.env文件..."
    
    if [[ ! -f ".env" ]]; then
        print_error ".env文件不存在"
        print_message "请先运行部署脚本创建.env文件"
        exit 1
    fi
    
    print_message ".env文件存在"
}

# 加载环境变量
load_env_vars() {
    print_step "加载环境变量..."
    
    if [[ -f ".env" ]]; then
        export $(grep -v '^#' .env | xargs)
        print_message "环境变量已加载"
    else
        print_error "无法加载.env文件"
        exit 1
    fi
}

# 检查数据库配置
check_db_config() {
    print_step "检查数据库配置..."
    
    local required_vars=("DB_USER" "DB_PASSWORD" "DB_HOST" "DB_PORT" "DB_NAME")
    local missing_vars=()
    
    for var in "${required_vars[@]}"; do
        if [[ -z "${!var}" ]]; then
            missing_vars+=("$var")
        else
            if [[ "$var" == "DB_PASSWORD" ]]; then
                print_message "$var: *** (已设置)"
            else
                print_message "$var: ${!var}"
            fi
        fi
    done
    
    if [[ ${#missing_vars[@]} -gt 0 ]]; then
        print_error "缺少数据库配置:"
        for var in "${missing_vars[@]}"; do
            print_error "  - $var"
        done
        return 1
    fi
    
    print_message "数据库配置检查通过"
    return 0
}

# 检查AI配置
check_ai_config() {
    print_step "检查AI配置..."
    
    local required_vars=("AI_PROVIDER" "AI_CHAT_URL" "AI_USERNAME" "AI_PASSWORD")
    local missing_vars=()
    
    for var in "${required_vars[@]}"; do
        if [[ -z "${!var}" ]]; then
            missing_vars+=("$var")
        else
            if [[ "$var" == "AI_PASSWORD" ]]; then
                print_message "$var: *** (已设置)"
            else
                print_message "$var: ${!var}"
            fi
        fi
    done
    
    if [[ ${#missing_vars[@]} -gt 0 ]]; then
        print_warning "缺少AI配置:"
        for var in "${missing_vars[@]}"; do
            print_warning "  - $var"
        done
        print_warning "AI功能可能无法正常工作"
        return 1
    fi
    
    print_message "AI配置检查通过"
    return 0
}

# 测试数据库连接
test_db_connection() {
    print_step "测试数据库连接..."
    
    if command -v mysql &> /dev/null; then
        if mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASSWORD" -e "SELECT 1;" &>/dev/null; then
            print_message "数据库连接测试成功"
            return 0
        else
            print_warning "数据库连接测试失败"
            print_warning "请检查数据库配置和网络连接"
            return 1
        fi
    else
        print_warning "mysql客户端未安装，跳过数据库连接测试"
        return 0
    fi
}

# 测试AI服务连接
test_ai_connection() {
    print_step "测试AI服务连接..."
    
    if command -v curl &> /dev/null; then
        if curl -s -f "$AI_CHAT_URL" &>/dev/null; then
            print_message "AI服务连接测试成功"
            return 0
        else
            print_warning "AI服务连接测试失败"
            print_warning "请检查AI服务配置和网络连接"
            return 1
        fi
    else
        print_warning "curl未安装，跳过AI服务连接测试"
        return 0
    fi
}

# 检查容器状态
check_container_status() {
    print_step "检查容器状态..."
    
    if docker ps | grep -q "yxyweb-app"; then
        print_message "YxYWeb容器正在运行"
        
        # 检查健康状态
        if curl -s -f http://localhost:8000/health &>/dev/null; then
            print_message "应用健康检查通过"
            return 0
        else
            print_warning "应用健康检查失败"
            return 1
        fi
    else
        print_warning "YxYWeb容器未运行"
        return 1
    fi
}

# 显示配置摘要
show_config_summary() {
    print_step "配置摘要..."
    
    echo ""
    echo "=========================================="
    echo "           配置摘要"
    echo "=========================================="
    echo ""
    echo "数据库配置:"
    echo "  主机: $DB_HOST:$DB_PORT"
    echo "  用户: $DB_USER"
    echo "  数据库: $DB_NAME"
    echo ""
    echo "AI配置:"
    echo "  提供商: $AI_PROVIDER"
    echo "  聊天URL: $AI_CHAT_URL"
    echo "  用户: $AI_USERNAME"
    echo ""
    echo "应用配置:"
    echo "  调试模式: $DEBUG"
    echo "  端口: 8000"
    echo ""
}

# 主函数
main() {
    echo "=========================================="
    echo "    YxYWeb 环境变量测试工具"
    echo "=========================================="
    echo ""
    
    # 检查.env文件
    check_env_file
    
    # 加载环境变量
    load_env_vars
    
    # 检查配置
    local db_ok=false
    local ai_ok=false
    
    if check_db_config; then
        db_ok=true
    fi
    
    if check_ai_config; then
        ai_ok=true
    fi
    
    # 测试连接
    if [[ "$db_ok" == "true" ]]; then
        test_db_connection
    fi
    
    if [[ "$ai_ok" == "true" ]]; then
        test_ai_connection
    fi
    
    # 检查容器状态
    check_container_status
    
    # 显示配置摘要
    show_config_summary
    
    echo "=========================================="
    if [[ "$db_ok" == "true" && "$ai_ok" == "true" ]]; then
        print_message "环境配置检查完成，配置正确！"
    else
        print_warning "环境配置检查完成，请检查上述警告信息"
    fi
    echo "=========================================="
    echo ""
}

# 执行主函数
main "$@" 